<template>
  <div>
    <mpvue-cropper
      ref="cropper"
      :option="cropperOpt"
      @ready="cropperReady"
      @beforeDraw="cropperBeforeDraw"
      @beforeImageLoad="cropperBeforeImageLoad"
      @beforeLoad="cropperLoad"
    ></mpvue-cropper>
    <div
      class="cropper-buttons">
      <div
        class="text-btn"
        @click="chooseTap">
        {{ cropperSrc ? '重新选择' : '选择照片' }}
      </div>
      <div
        class="text-btn"
        @click="getCropperImage">
        确定
      </div>
    </div>
  </div>
</template>

<script>
  // import { getMemberDetails, saveMemberDetails } from '@/api/personal'
  import MpvueCropper from 'mpvue-cropper'
  let weCropper
  export default {
    data() {
      return {
        cropperSrc: '',
        cropperOpt: {},
        files: [],
        isUploadFinish: false,
        queryType: ''
      }
    },
    components: {
      MpvueCropper
    },
    onLoad() {
      // 初始化data
      Object.assign(this.$data, this.$options.data())
      const device = this.$pt.getSystemInfoSync()
      const width = device.windowWidth
      const height = device.windowHeight - 100
      this.cropperOpt = {
        id: 'cropper',
        targetId: 'targetCropper',
        pixelRatio: device.pixelRatio,
        width,
        height,
        scale: 2.5,
        zoom: 8,
        cut: {
          x: 0,
          y: 0,
          width: width,
          height: height
        }
      }
    },
    mounted() {
      weCropper = this.$refs.cropper
      this.chooseTap()
    },
    // 监听上传是否完成
    watch: {
      isUploadFinish(val) {
        if (this.isUploadFinish) {
          this.doSave()
        }
      }
    },
    methods: {
      cropperReady(...args) {
        this.$pt.setStorageSync('__picUrl__', 'none')
        console.log('cropper ready!')
      },
      cropperBeforeImageLoad(...args) {
        console.log('before image load')
      },
      cropperLoad(...args) {
        console.log('image loaded')
      },
      cropperBeforeDraw(...args) {
        // Todo: 绘制水印等等
      },
      chooseTap() {
        const that = this
        that.$pt.chooseImage({
          count: 1, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: (res) => {
            const src = res.tempFilePaths[0]
            //  获取裁剪图片资源后，给data添加src属性及其值
            if (src) {
              weCropper.pushOrigin(src)
              that.cropperSrc = src
            }
          }
        })
      },
      getCropperImage() {
        const that = this
        weCropper.getCropperImage()
          .then((src) => {
            if (!that.cropperSrc) {
              that.$utils.showToast({ title: '请先选择照片' })
              return
            }
            that.files.push(src)
            that.doSave()
          })
          .catch(e => {
            console.error('获取图片失败')
          })
      },
      doSave() {
        if (!this.isUploadFinish) {
          if (this.files.length === 0) return this.$utils.showToast({ title: '请选择要上传的照片' })
          this.$utils.showToast({
            title: '图片上传中',
            icon: 'loading',
            duration: 150000,
            mask: true
          })
          // 开始上传文件
          this.doUpload()
        } else {
          // 上传完成，清除数据
          this.files = []
          // 保存数据
          setTimeout(() => {
            this.$pt.navigateBack({ delta: -1 })
          }, 500)
        }
      },
      doUpload() {
        const that = this
        let finishCount = 0
        this.files.forEach(file => {
          // 使用微信上传（只能单张上传）
          const uploadTask = that.$pt.uploadFile({
            url: process.env.BASE_API + '/common/uploadFiles',
            filePath: file,
            name: 'files',
            success(res) {
              const result = JSON.parse(res.data)
              if (result.code === 101) {
                let from = that.getCurrentPage().query.from
                let data = {
                  url: result.data[0],
                  from: from
                }
                that.$pt.setStorageSync('__picUrl__', data)
              } else {
                that.$utils.showToast({ title: '图片上传发生错误:' + result.msg })
                finishCount--
              }
            },
            complete() {
              finishCount++
              if (that.files.length === finishCount) {
                that.isUploadFinish = true
              }
            }
          })
          uploadTask.onProgressUpdate((res) => {
            console.log('上传进度', res.progress)
          })
        })
      }
    }
  }
</script>

<style scoped>
  .cropper-buttons {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 50px;
    padding: 0 10px;
    box-sizing: border-box;
    line-height: 50px;
  }

  .cropper-buttons {
    background-color: rgba(0, 0, 0, 0.95);
  }

  .text-btn {
    height: 30px;
    line-height: 30px;
    padding: 0 12px;
    border-radius: 2px;
    color: #ffffff;
  }
</style>
